<!--标记动画-->
<!--animating-->
/* eslint-disable */
<template>
  <div>
    <div id="map" class="mapC"></div>
    <div class="select_c">
      <div class="block">
        <span class="demonstration">默认</span>
        <el-slider @change="sliderChange" v-model="value1"></el-slider>
      </div>
      <el-button @click="changeBut">{{labelD}}</el-button>
      <el-button @click="changeAdd">添加</el-button>
    </div>
  </div>
</template>

<script>
import 'ol/ol.css'
import Feature from 'ol/Feature'
import Map from 'ol/Map'
import Point from 'ol/geom/Point'
import Polyline from 'ol/format/Polyline'
import VectorSource from 'ol/source/Vector'
import View from 'ol/View'
import XYZ from 'ol/source/XYZ'
import {
  // Circle as CircleStyle,
  // Fill,
  Icon,
  Stroke,
  Style
} from 'ol/style'
import {Tile as TileLayer, Vector as VectorLayer} from 'ol/layer'
import {getVectorContext} from 'ol/render'
export default {
  name: 'index',
  data () {
    return {
      value1: 10,
      raster: null,
      raster2: null,
      route: null,
      routeCoords: null,
      labelD: '开始',
      styles: null,
      routeFeature: null,
      geoMarker: null,
      startMarker: null,
      vectorLayer: null,
      speed: '',
      startTime: '',
      endMarker: null,
      animating: false,
      srcUrl: require('./icon.png'),
      srcUrlcat: require('./cat.png'),
      center: [-5639523.95, -3501274.52],
      result: {'routes': [{'geometry': 'hldhx@lnau`BCG_EaC??cFjAwDjF??uBlKMd@}@z@??aC^yk@z_@se@b[wFdE??wFfE}NfIoGxB_I\\gG}@eHoCyTmPqGaBaHOoD\\??yVrGotA|N??o[N_STiwAtEmHGeHcAkiA}^aMyBiHOkFNoI`CcVvM??gG^gF_@iJwC??eCcA]OoL}DwFyCaCgCcCwDcGwHsSoX??wI_EkUFmq@hBiOqBgTwS??iYse@gYq\\cp@ce@{vA}s@csJqaE}{@iRaqE{lBeRoIwd@_T{]_Ngn@{PmhEwaA{SeF_u@kQuyAw]wQeEgtAsZ}LiCarAkVwI}D??_}RcjEinPspDwSqCgs@sPua@_OkXaMeT_Nwk@ob@gV}TiYs[uTwXoNmT{Uyb@wNg]{Nqa@oDgNeJu_@_G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AkdAmhAyTcVkFeEoKiH}l@kp@wg@sj@ku@ey@uh@kj@}EsFmG}Jk^_r@_f@m~@ym@yjA??a@cFd@kBrCgDbAUnAcBhAyAdk@et@??kF}D??OL'}]}
    }
  },
  mounted () {
    this.initMap()
    this.getData()
  },
  methods: {
    initMap () {
      this.raster = new TileLayer({
        name: 'map1',
        title: 'map1',
        source: new XYZ({
          url: '/mapServe/tdt/map/{z}/{x}/{y}.png'
        }),
        visible: true
      })
      this.raster2 = new TileLayer({
        name: 'mapi2',
        title: 'mapi2',
        source: new XYZ({
          url: '/mapServe/tdt/mapi/{z}/{x}/{y}.png'
        }),
        visible: true
      })
      this.map = new Map({
        layers: [this.raster, this.raster2],
        target: 'map',
        view: new View({
          center: [-5639523.95, -3501274.52],
          zoom: 10,
          minZoom: 2,
          maxZoom: 19
          // projection: 'EPSG:4326'
        })
      })
    },
    getData () {
      let that = this
      // 从接口拿数据
      // fetch('zlocal/data/polyline/route.json').then(function (response) {
      // response.json().then(function (result) {
      // ================================
      // 测试本地数据
      const polyline = that.result.routes[0].geometry
      that.route = new Polyline({
        factor: 1e6
      }).readGeometry(polyline, {
        dataProjection: 'EPSG:4326',
        featureProjection: 'EPSG:3857'
      })
      that.routeCoords = that.route.getCoordinates()
      that.routeFeature = new Feature({
        type: 'route',
        geometry: that.route
      })
      that.geoMarker = new Feature({
        type: 'geoMarker',
        geometry: new Point(that.route.getCoordinateAt(0))
      })
      that.startMarker = new Feature({
        type: 'icon',
        geometry: new Point(that.route.getCoordinateAt(0))
      })
      that.endMarker = new Feature({
        type: 'icon',
        geometry: new Point(that.route.getCoordinateAt(1))
      })
      that.styles = {
        'route': new Style({
          stroke: new Stroke({
            width: 6,
            color: [237, 212, 0, 0.8]
          })
        }),
        'icon': new Style({
          image: new Icon({
            anchor: [0.5, 1],
            src: that.srcUrl
          })
        }),
        'geoMarker': new Style({
          // image: new CircleStyle({
          //   radius: 7,
          //   fill: new Fill({color: 'black'}),
          //   stroke: new Stroke({
          //     color: 'white',
          //     width: 2
          //   })
          // })
          image: new Icon({
            anchor: [0.5, 1],
            rotation: -Math.atan2(that.routeCoords[0][1] - that.routeCoords[1][1], that.routeCoords[0][0] - that.routeCoords[1][0]),
            src: that.srcUrlcat,
            scale: 0.5
          })
        })
      }
      // })
      // })
    },
    sliderChange (val) {
      console.log(val)
    },
    changeBut () {
      this.startAnimation()
    },
    changeAdd () {
      let that = this
      that.vectorLayer = new VectorLayer({
        source: new VectorSource({
          features: [that.routeFeature, that.geoMarker, that.startMarker, that.endMarker]
        }),
        style: function (feature) {
          // hide geoMarker if animation is active
          if (that.animating && feature.get('type') === 'geoMarker') {
            return null
          }
          return that.styles[feature.get('type')]
        }
      })

      that.map.addLayer(that.vectorLayer)
    },
    startAnimation () {
      if (this.animating) {
        this.stopAnimation(false)
      } else {
        this.animating = true
        this.startTime = new Date().getTime()
        this.speed = this.value1
        // startButton.textContent = 'Cancel Animation'
        this.labelD = '停止'
        // hide geoMarker
        this.geoMarker.changed()
        // just in case you pan somewhere else
        this.map.getView().setCenter(this.center)
        this.vectorLayer.on('postrender', this.moveFeature)
        this.map.render()
      }
    },
    stopAnimation (ended) {
      this.animating = false
      // startButton.textContent = 'Start Animation'
      this.labelD = '开始'
      // if animation cancelled set the marker at the beginning
      const coord = this.route.getCoordinateAt(ended ? 1 : 0)
      this.geoMarker.getGeometry().setCoordinates(coord)
      // remove listener
      this.vectorLayer.un('postrender', this.moveFeature)
    },
    moveFeature (event) {
      const vectorContext = getVectorContext(event)
      const frameState = event.frameState
      console.log(this.routeCoords.length, 'routeCoords')
      if (this.animating) {
        const elapsedTime = frameState.time - this.startTime
        console.log(elapsedTime, 'elapsedTime')
        const distance = (this.speed * elapsedTime) / 1e6
        if (distance >= 1) {
          this.stopAnimation(true)
          return
        }
        const currentPoint = new Point(this.route.getCoordinateAt(distance))
        const feature = new Feature(currentPoint)
        // 计算小车的实时旋转================start
        let index = Math.round(this.speed * elapsedTime / 1000)
        let dx = ''
        let dy = ''
        let rotation = ''
        let carStyle = null
        if (this.routeCoords[index] && this.routeCoords[index + 1]) {
          dx = this.routeCoords[index][0] - this.routeCoords[index + 1][0]
          dy = this.routeCoords[index][1] - this.routeCoords[index + 1][1]
          rotation = Math.atan2(dy, dx)
          carStyle = new Style({
            image: new Icon({
              src: this.srcUrlcat,
              rotateWithView: false,
              rotation: -rotation,
              scale: 0.5
            })
          })
          vectorContext.drawFeature(feature, carStyle)
          // 计算小车的实时旋转================end
        } else {
          vectorContext.drawFeature(feature, this.styles.geoMarker)
        }
      }
      // tell OpenLayers to continue the postrender animation
      this.map.render()
    }
  }
}
</script>

<style scoped>
  .mapC{
    width: 100vw;
    height: 100vh;
  }
  .select_c{
    position: absolute;
    top: 0;
    left: 0;
  }
  .block{
    width: 12vw;
    padding: 20px;
    float: left;
  }
</style>
